﻿using System.IO;
using System.Linq;
using System.Text;
using NAnt.Core;
using NAnt.Core.Attributes;
using NAnt.Core.Types;

namespace LeanUi.ImageBundle
{
    /// <summary>
    /// Inlines Javascript-Files with following content:
    /// 
    /// document.write(
    /// '<script type="text/javascript" src="scripts/jquery-1.4.2.js"></script>' +
    /// '<script type="text/javascript" src="scripts/jquery.validate.js"></script>');
    /// 
    /// </summary>
    [TaskName("scriptcombiner")]
    public class ScriptCombinerTask : Task
    {
        private string _extension = ".debug.js";
        private string _replacement = ".js";


        [TaskAttribute("basepath"), StringValidator(AllowEmpty = false)]
        public string BasePath { get; set; }

        [TaskAttribute("extension"), StringValidator(AllowEmpty = false)]
        public string Extension
        {
            get { return _extension; }
            set { _extension = value; }
        }

        [TaskAttribute("replacement"), StringValidator(AllowEmpty = false)]
        public string Replacement
        {
            get { return _replacement; }
            set { _replacement = value; }
        }


        private FileSet _fileset = new FileSet();

        /// <summary>
        /// All the files in the file set will be deleted.
        /// </summary>
        [BuildElement("fileset")]
        public FileSet FileSet
        {
            get { return _fileset; }
            set { _fileset = value; }
        }

        protected override void ExecuteTask()
        {
            if (FileSet.BaseDirectory == null) {
                FileSet.BaseDirectory = new DirectoryInfo(Project.BaseDirectory);
            }

            foreach (string path in _fileset.FileNames)
            {
                Log(Level.Verbose, "filename: " + path);
                var allLines = File.ReadAllLines(path);
                if (allLines.First().Contains("document.write(")) {
                    string res = CombineJavascripts(BasePath, allLines);
                    File.WriteAllText(path.Replace(_extension, _replacement), res);
                }
            }
        }

        private string CombineJavascripts(string basepath, string[] lines)
        {
            var sb = new StringBuilder();
            foreach (var line in lines.Where(x => x.Contains("src=\"")))
            {
                var path = line.ExtractInner("src=\"", "\"").TrimStart('\\','/');
                var fullpath = Path.Combine(basepath, path);
                var content = File.ReadAllText(fullpath);
                sb.AppendLine(content);
            }
            return sb.ToString();
        }
    }
}
